package com.demo.springbooot_demo.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.Map;

public class TokenManager {
    private static long tokenExpiration = 7*24*60*60*1000 ; //7天时间
    private static String tokenSignKey ="demo-sign"; //加密串，随便定义但不能泄露

    /**
     * 根据用户Id生成token串
     * @param userId 用户Id
     * @return
     */
    public static String createToken(String userId){

        return Jwts.builder()
                .setHeaderParam("typ","jwt")
                .setHeaderParam("alg","HS256")
                .setIssuedAt(new Date())  //颁布时间
                .setIssuer("system")  //颁布人
                .setSubject(userId)    //主题
                //.claim("key","value") 自定义荷载
                .setExpiration(new Date(System.currentTimeMillis()+tokenExpiration)) //失效时间
                .signWith(SignatureAlgorithm.HS256,tokenSignKey) //验签加密
                .compact();
    }

    /**
     * 根据token串返回用户Id
     * @param token
     * @return
     */
    public static Claims decodeToken(String token){
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        return claimsJws.getBody() ;//{iat=1726625659, iss=system, sub=1, exp=1727230459}
    }


}
